package com.scalar.chiptrack.adaptor.backlog;
import com.scalar.ScalarException;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.StringUtils;

import com.enterprisedt.net.ftp.FTPClient;
import com.enterprisedt.net.ftp.FTPTransferType;
import com.enterprisedt.net.ftp.FTPConnectMode;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;


public class BACKLOGFTPAdaptor extends JobHandler implements AdaptorConstants
{
    private static final String BACKLOG_FTP_HOST    = "64.139.54.8";
    private static final int BACKLOG_PORT           = 21;
    private static final String m_username          = "scalar";
    private static final String m_password          = "ontrack20";
    private Logger m_adaptorLogger                  = null;
    private String filePath                         = null;

    private static final String LINE_SEPARATOR = System.getProperty( "line.separator" );
    /**
     *
     * @throws ScalarException
     */
    public BACKLOGFTPAdaptor() throws ScalarException
    {
        String logDirectory;
        String logFileName = "backlog_adptor%u.log";
        String logPrefix = "Backlog_Adaptor";
        String level = "debug";
        int maxFileSize = 1024 * 500;
        int fileCount = 1;

        filePath = System.getProperty("salesOrdersSheet.directory");
        filePath = ConfigManager.getSalesOrdersSheetDirectory();
        System.out.println("filePath = " + filePath);
        logDirectory = new File( filePath ).getParent();
        try
        {
            m_adaptorLogger = new Logger( logDirectory, logFileName, logPrefix, level, maxFileSize, fileCount );
        }
        catch ( Exception e )
        {
            e.printStackTrace();
        }

    }
    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main( String[] args ) throws Exception
    {
        new BACKLOGFTPAdaptor().execute();
    }
    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {

        printHeader();


        FTPClient ftp = login( BACKLOG_FTP_HOST, BACKLOG_PORT, m_username, m_password );
        log( "Successfully logged in to " + BACKLOG_FTP_HOST );
        System.out.println( "Successfully logged in to " + BACKLOG_FTP_HOST );

        downloadBacklogFiles( ftp );
        // Log out
        logout( ftp );
        log( "\nSuccessfully logged out from Backlog Ftp Site" );
        System.out.println( "\nSuccessfully logged out from  backlog FTP Site" );

    }

    /**
     *
     * @param message
     */
    private void log( String message )
    {

        if ( message == null ) return;

        if ( m_adaptorLogger != null )
        {
            synchronized ( m_adaptorLogger )
            {
                m_adaptorLogger.logDebug( message + LINE_SEPARATOR );
            }
        }
        else
        {
            System.out.println( message );
        }
    }


    private FTPClient login( String host, int port, String m_username, String m_password ) throws Exception
    {

        FTPClient ftp = new FTPClient( host, port );
        ftp.login( m_username, m_password );
        ftp.debugResponses( false );
        ftp.setType( FTPTransferType.BINARY );
        // active does not allows me connect to ftp site even any proxy lies in path.
        ftp.setConnectMode( FTPConnectMode.PASV );
        return ftp;
    }

    private void logout( FTPClient ftp ) throws Exception
    {
        if ( ftp == null )
        {
            return;
        }

        try
        {
            ftp.quit();
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From Backlog FTP Site" + ignore );
            throw ignore;
        }

        ftp = null;
    }

    private void downloadBacklogFiles( FTPClient ftp ) throws Exception
    {
        String[] listings = ftp.dir();


        if ( ( listings == null ) || ( listings.length == 0 ) )
        {
            return;
        }

        byte[] buf = null;

        FileOutputStream fileOutputStream = null;

        try
        {

            String tempFileName = null;

            System.out.println( "\tDownloading backlog  files...." );

            /* To get the latest maxdate */
            for ( int i = 0; i < listings.length; i++ )
            {

                if ( ( listings[i].startsWith( "BKLOG" ) ) )
                {
                    if ( tempFileName == null )
                    {
                        tempFileName = listings[i];
                    }
                    else
                    {
                        String strDate1 = tempFileName.substring( 5, 14 );
                        String strDate2 = listings[i].substring( 5, 14 );

                        strDate1 = StringUtils.formatDate( strDate1, "yyMMdd-HH", "yyyy-MM-dd HH:mm:ss" );
                        strDate2 = StringUtils.formatDate( strDate2, "yyMMdd-HH", "yyyy-MM-dd HH:mm:ss" );

                        java.util.Date date1 = StringUtils.format( strDate1, "yyyy-MM-dd HH:mm:ss");
                        java.util.Date date2 = StringUtils.format( strDate2, "yyyy-MM-dd HH:mm:ss");

                        if ( date1 != null && date2 != null )
                        {
                            if ( date2.compareTo( date1 ) > 0 )
                            {
                                tempFileName = listings[i];
                            }
                        }
                    }
                }
            }

            if ( tempFileName != null )
            {
                log( "\n downloading file " + tempFileName + " to " + filePath + " directory... " );
                System.out.println( " downloading file " + tempFileName + " to " + filePath + " directory... " );
                buf = ftp.get( tempFileName );
                fileOutputStream = new FileOutputStream( filePath );
                fileOutputStream.write( buf );
                System.out.println( "done" );
            }

        }
        catch ( Exception e )
        {
            log( "Exception while downloading......... " + e );
            throw e;
        }

        finally
        {
            if ( fileOutputStream != null )
            {
                try
                {
                    fileOutputStream.close();
                }
                catch ( IOException ignore )
                {
                }
            }
        }
    }
    /**
     *
     */
    private void printHeader()
    {

        String message = "\n\n+----------- Running BACKLOGFTPAdaptor on " + new java.util.Date( System.currentTimeMillis() ) + " -------------+\n" +
                "\n+---------------------------------------------------------------+\n" +
                "+                                                                \n" +
                "+                 BACKLOG FTP Adaptor - Beta                       \n" +
                "+                                                                \n" +
                "+    Copy Right (C) 2005 - ScalarSoft Inc., All rights reserved.  \n" +
                "+                                                                \n" +
                "+---------------------------------------------------------------+\n";
        System.out.println( message );
        log( message );

    }

}